package com.store.app.adapter;

import android.annotation.SuppressLint;
import android.content.Context;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import com.store.app.R;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * 礼券明细适配器
 */
public class TokenrecordListAdapter extends BaseAdapter{
	private Context context;		//上下文对象引用
	private  JSONArray data= new JSONArray();
	private int pos = -1;			//列表位置
	/**
	 * 构造函数
	 * @param context	上下文
	 */
	public TokenrecordListAdapter(Context context, JSONArray data) {
		this.context = context;
		this.data=data;
	}
	@Override
	public int getCount() {
		// TODO Auto-generated method stub
		return data.length();
	}


	@Override
	public Object getItem(int position) {
		return position;
	}
	@Override
	public long getItemId(int position) {
		return position;
	}

	@SuppressLint("NewApi")
	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		ViewHolder viewHolder = null;
		if(convertView == null)
		{
			viewHolder = new ViewHolder();
			convertView = LayoutInflater.from(context).inflate(R.layout.tokenrecordlist, null);
			viewHolder.amount = (TextView) convertView.findViewById(R.id.amount);
			viewHolder.time = (TextView) convertView.findViewById(R.id.time);
			viewHolder.detail = (TextView) convertView.findViewById(R.id.detail);
			convertView.setTag(viewHolder);			//表示给View添加一个格外的数据，
		} else {
			viewHolder = (ViewHolder)convertView.getTag();//通过getTag的方法将数据取出来
		}

		try {
			String symbol;

			String value = ((JSONObject) data.get(position)).getString("amount");
			if(!TextUtils.isEmpty(value)) {
				value = value.split("\\.")[0];
				if (value.contains("-")) {
					symbol = "";
					//viewHolder.amount.setTextColor(Color.parseColor("#8cc83a"));
				} else {
					//viewHolder.amount.setTextColor(Color.parseColor("#f96116"));
					symbol = "+";
				}
			viewHolder.amount.setText(symbol+value);
			}
			String s_date=((JSONObject) data.get(position)).getString("tracked_date");
			//String s_date=((JSONObject) data.get(position)).getString("transaction_date");

			if(!TextUtils.isEmpty(s_date)){
			viewHolder.time.setText(s_date);}
			String detalStr = ((JSONObject) data.get(position)).getString("detail");
			if(!TextUtils.isEmpty(detalStr)){
				viewHolder.detail.setText(detalStr);
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}


		return convertView;
	}
	/**
	 * 定义一个内部类
	 * 声明相应的控件引用
	 *
	 */
	public class ViewHolder {

		public TextView amount;			//金额
		public TextView time;			//时间
		public TextView detail;	//属性（消费还是充值）
	}
}
